package com.usian.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.usian.common.constants.AdminConstans;
import com.usian.model.article.pojos.ApAuthor;
import com.usian.model.base.BaseServiceImpl;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.pojos.WmUser;
import com.usian.model.user.dtos.AuthDto;
import com.usian.model.user.pojos.ApUser;
import com.usian.model.user.pojos.ApUserRealname;
import com.usian.user.feign.ArticleFeign;
import com.usian.user.feign.WemediaFeign;
import com.usian.user.mapper.ApUserMapper;
import com.usian.user.mapper.ApUserRealnameMapper;
import com.usian.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.LinkedHashMap;

@Service
public class ApUserRealnameServiceImpl extends BaseServiceImpl<ApUserRealnameMapper, ApUserRealname>
implements ApUserRealnameService {

    @Autowired
    private ArticleFeign articleFeign;
    @Autowired
    private WemediaFeign wemediaFeign;
    @Resource
    private ApUserMapper userMapper;

    @Override
    public ResponseResult findPage(AuthDto dto) {
        if (dto==null || (dto.getStatus()!=null && (dto.getStatus()!=0 && dto.getStatus()!=1 && dto.getStatus()!=2 && dto.getStatus()!=9))){
            return paramError;
        }
        LambdaQueryWrapper<ApUserRealname> queryWrapper = Wrappers.<ApUserRealname>lambdaQuery().eq(ApUserRealname::getStatus, dto.getStatus() != null ? dto.getStatus() : 1);
        Page<ApUserRealname> page = new Page<>(dto.getPage(),dto.getSize());
        IPage<ApUserRealname> page1 = page(page, queryWrapper);
        PageResponseResult result = new PageResponseResult(dto.getPage(),dto.getSize(),(int)page1.getTotal());
        result.setData(page1.getRecords());
        result.setCode(AppHttpCodeEnum.SUCCESS.getCode());
        return result;
    }

    @GlobalTransactional
    @Transactional
    @Override
    public ResponseResult updateStatusById(AuthDto dto) {
        if (dto==null || dto.getStatus()==null || dto.getId()==null) return paramError;
        if (dto.getStatus() != AdminConstans.FAIL_AUTH && dto.getStatus() !=AdminConstans.PASS_AUTH) return paramError;
        //根据操作行为修改认证表中的状态
        ApUserRealname realname = getById(dto.getId());
        if (realname==null) return notExits;
        try {
            BeanUtils.copyProperties(realname,dto);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        if(StringUtils.isNotEmpty(dto.getMsg())) realname.setReason(dto.getMsg());
        updateById(realname);
        if(dto.getStatus() ==AdminConstans.PASS_AUTH){
            //根据认证id查询到用户id，把用户的flag修改为1(即自媒体人)
            ApUser apUser = userMapper.selectById(realname.getUserId());
            if (apUser==null) return notExits;
            apUser.setFlag((short)1);
            userMapper.updateById(apUser);
            //向自媒体表插入数据，根据用户表去同步
            WmUser wmUser = wemediaFeign.findByName(apUser.getName());
            if (wmUser==null){
                wmUser = new WmUser();
                wmUser.setApUserId(apUser.getId());
                wmUser.setName(apUser.getName());
                wmUser.setPassword(apUser.getPassword());
                wmUser.setSalt(apUser.getSalt());
                wmUser.setNickname("新自媒体人");
                wmUser.setPhone(apUser.getPhone());
                wmUser.setStatus(9);
                wmUser.setType(1);
                wmUser.setLoginTime(new Date());
                wmUser.setCreatedTime(new Date());
                ResponseResult result = wemediaFeign.save(wmUser);
                Object data = result.getData();
                if (data instanceof LinkedHashMap){
                    Integer id = (Integer) ((LinkedHashMap) data).get("id");
                    wmUser.setId(id);
                }
            }

            //向作者表插入数据，根据用户表去同步
            ApAuthor author = articleFeign.findByUserId(apUser.getId());
            if (author==null){
                author=new ApAuthor();
                author.setName(apUser.getName());
                author.setType(2);
                author.setUserId(apUser.getId());
                author.setCreatedTime(new Date());
                author.setWmUserId(wmUser.getId());
                ResponseResult save = articleFeign.save(author);
                //回调更新自媒体人表的作者id
                Object data = save.getData();
                if (data instanceof LinkedHashMap){
                    Integer id = (Integer) ((LinkedHashMap) data).get("id");
                    wmUser.setApAuthorId(id);
                }
                wemediaFeign.updateAuthorId(wmUser);
            }
//            int c=100/0;
            return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS,"认证成功");
        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS,"认证失败");
        }

    }
}
